﻿def synchronization_function(dialog,projectID)
    #以下编写上传skp文件方法，参数为“projectId”

    puts "---------------------------------------------------"
    mod = Sketchup.active_model # Open model
    skps=File.join(Sketchup.find_support_file('Plugins'), 'skps')
    dir=Dir.mkdir(skps) unless File.exist?(skps)
    status1 = mod.save "#{skps}\\project#{projectID}.skp"
    model_file ="#{skps}\\project#{projectID}.skp"
    filename = File.basename(model_file)
    boundary = "----RubyMultipartClient#{rand(1000000)}ZZZZZ"

     # The folderId param in the API contains the ID of the folder for the upload
    # param = { projectId: 4 }
    data = []
    data << "Content-Type: multipart/form-data; boundary=#{boundary}\r\n\r\n"
    data << "--#{boundary}\r\n"
     # The field in the API to upload the file is called filename
    data << "Content-Disposition: form-data; name=\"skp\"; filename=\"#{filename}\"\r\n\r\n"
    File.open(model_file, "rb:BINARY") { |file|
       contents = file.read
       data << contents
    }
    #data << "--#{boundary}\r\n"
     # The folderId param is added to the payload (see my POSTMAN working solution)
    #data << "Content-Disposition: form-data; name=\"projectId\"\r\n\r\n"
    #data << param.to_json

    data << "\r\n\r\n--#{boundary}--\r\n"

    data.each { |line|
       line.force_encoding(Encoding::BINARY)
    }

    payload = data.join

    headers = {}
    headers['Content-Type'] = "multipart/form-data; boundary=#{boundary}"
    headers

     # The field Authorization in the header contains the authorization token for the request
    #headers = { 'Content-Type' => "multipart/form-data; boundary=#{boundary}" }
     # connect_host is the host of my DB
    url = "http://dev.solarpv.top/api/client/project/upload?projectId=#{projectID}"
    request = Sketchup::Http::Request.new(url, Sketchup::Http::POST)
    request.headers = headers
    request.body = payload
    request.start do |req, res|
       # Not entering
     #  p res
     #  p res.status_code
     #  puts res.body
       json_upload_SKP=JSON.parse(res.body)
       upload_SKP_status=json_upload_SKP['status']
       upload_SKP_message=json_upload_SKP['message']
       p upload_SKP_status
       p upload_SKP_message
       #UI.messagebox("stats:#{upload_SKP_status} message:#{upload_SKP_message}")#测试字符串
       dialog.execute_script("synchronizationStats(#{upload_SKP_status},#{upload_SKP_message}'同步成功')")
       end

end